package com.scpii.api.common.auth.expression.method;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.core.Authentication;

import com.scpii.api.common.Constants;
import com.scpii.api.common.exception.UserDeniedAuthorizationException;

public class RoleCheckPreInvocationAuthorizationAdvice extends
		ExpressionBasedPreInvocationAdvice {

	@Override
	public boolean before(Authentication authentication, MethodInvocation mi,
			PreInvocationAttribute attr) {
		Boolean isAllowed = super.before(authentication, mi, attr);
		if (mi.getMethod().isAnnotationPresent(PreAuthorize.class)) {
			PreAuthorize preAuth = mi.getMethod().getAnnotation(
					PreAuthorize.class);
			String roleClientStr = "hasRole('"
					+ Constants.ROLES.get("ROLE_CLIENT") + "')";
			if (isAllowed == false && !roleClientStr.equals(preAuth.value())) {
				throw new UserDeniedAuthorizationException(
						"require user authentication");
			}
		}
		return isAllowed;
	}
}
